package com.heima.media.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.media.entity.WmSensitive;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmSensitiveService;
import com.netflix.ribbon.proxy.annotation.Http;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private IAuditService auditService;
    @Autowired
    private IWmSensitiveService wmSensitiveService;

    @GetMapping("/audit/{id}")
    public ResponseResult audit(@PathVariable("id") Integer id) {
        auditService.audit(id);
        return ResponseResult.okResult();
    }

    @PostMapping("/upload")
    public String upload(MultipartFile file) throws Exception{
        EasyExcel.read(file.getInputStream(), WmSensitive.class,new PageReadListener<WmSensitive>(dataList ->{
            for (WmSensitive demoData : dataList) {
                //判断这个敏感词是否已经存在表中了
                LambdaQueryWrapper<WmSensitive> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(WmSensitive::getSensitives,demoData.getSensitives());
                WmSensitive one = wmSensitiveService.getOne(queryWrapper);
                if(one == null){
                    demoData.setCreatedTime(new Date());
                    wmSensitiveService.save(demoData);
                }

            }
        })).sheet().doRead();
        return "Success";
    }

    @GetMapping("/download")
    public void download(HttpServletResponse response) throws Exception{
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=sensitive.xlsx");
        EasyExcel.write(outputStream,WmSensitive.class).sheet("导出的敏感词").doWrite(() ->{
            return wmSensitiveService.list();
        });

    }
}
